package com.luhuiguo.sso.entity;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

import com.luhuiguo.sso.entity.AuditableEntity;

@Entity
@Table(name = "t_approval")
@NamedQueries( {
		@NamedQuery(name = "approval.byUserAndSite", query = "select t from Approval t where t.user=:user and t.site=:site"),
		@NamedQuery(name = "approval.byUserAndUrl", query = "select t from Approval t where t.user=:user and t.site.url=:url"),
		@NamedQuery(name = "approval.byUsernameAndUrl", query = "select t from Approval t where t.user.username=:username and t.site.url=:url") })
public class Approval extends AuditableEntity {

	private static final long serialVersionUID = 4180331511916877572L;

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO)
	private Long id;

	@ManyToOne
	private Site site;

	@ManyToOne
	private User user;

	@ManyToOne
	private Persona persona;

	private boolean alwaysAllow;

	public Approval() {
		super();
	}

	/**
	 * @param site
	 * @param user
	 * @param persona
	 * @param alwaysAllow
	 */
	public Approval(Site site, User user, Persona persona, boolean alwaysAllow) {
		super();
		this.site = site;
		this.user = user;
		this.persona = persona;
		this.alwaysAllow = alwaysAllow;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Site getSite() {
		return site;
	}

	public void setSite(Site site) {
		this.site = site;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Persona getPersona() {
		return persona;
	}

	public void setPersona(Persona persona) {
		this.persona = persona;
	}

	public boolean isAlwaysAllow() {
		return alwaysAllow;
	}

	public void setAlwaysAllow(boolean alwaysAllow) {
		this.alwaysAllow = alwaysAllow;
	}

	@Override
	public boolean equals(Object other) {
		if (!(other instanceof Approval)) {
			return false;
		}
		Approval castOther = (Approval) other;
		return new EqualsBuilder().append(this.getSite(), castOther.getSite())
				.append(this.getUser(), castOther.getUser()).isEquals();
	}

	@Override
	public int hashCode() {
		return new HashCodeBuilder().append(getSite()).append(getUser())
				.toHashCode();
	}

	@Override
	public String toString() {
		ToStringBuilder sb = new ToStringBuilder(this,
				ToStringStyle.SIMPLE_STYLE).append("site", this.site).append(
				"user", this.user).append("persona", this.persona).append(
				"alwaysAllow", this.alwaysAllow);
		return sb.toString();
	}

}
